﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FIFP.DashBoard.Views;
using System.Windows.Browser;
using FIFP.DashBoard.Helper;
using System.Globalization;
using System.Threading;

namespace FIFP.DashBoard
{
    public partial class App : Application
    {        
        #region Variables
        private static string _customPageName = string.Empty;
        private static string _loginUserId = string.Empty;
        private static string _loginUserName = string.Empty;
        private static string _loginEmail = string.Empty;
        private static bool _bMultiDBCallError = false;
        private static string _aoServicesUri = string.Empty;
        private static string _customMainPageName = string.Empty;
        private static string _loginPhone = string.Empty;
        private static string _portalUrl = string.Empty;
        private static string _userGroupId = string.Empty;
        private static string _queryStringId = string.Empty;
        private static string _helpFilePath = string.Empty;
        #endregion

        #region Properties
        public enum NavType { NoDefined = 0, Import = 1 };
        public static string CustomPageName
        {
            get
            {
                return _customPageName;
            }
            set { _customPageName = value; }
        }
        public static string LoginUserId
        {
            get { return _loginUserId; }
            set { _loginUserId = value; }
        }
        public static string LoginUserName
        {
            get { return _loginUserName; }
            set { _loginUserName = value; }
        }       
        public static string LoginEmail
        {
            get { return _loginEmail; }
            set { _loginEmail = value; }
        }

        public static string AoServicesUri
        {
            get
            {
                return _aoServicesUri;
            }
            set { _aoServicesUri = value; }
        }

        public static string CustomMainPageName
        {
            get
            {
                return _customMainPageName;
            }
            set { _customMainPageName = value; }
        }

        public static string PortalUrl
        {
            get
            {
                return _portalUrl;
            }
            set { _portalUrl = value; }
        }
        public static string LoginPhone
        {
            get { return _loginPhone; }
            set { _loginPhone = value; }
        }

        public static string UserGroupId
        {
            get { return _userGroupId; }
            set { _userGroupId = value; }
        }

        public static string QueryStringId
        {
            get { return _queryStringId; }
            set { _queryStringId = value; }
        }

        public static string HelpFilePath
        {
            get { return _helpFilePath; }
            set { _helpFilePath = value; }
        }

        #endregion

        #region Constructor
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;
            CultureInfo ci = new CultureInfo(Thread.CurrentThread.CurrentCulture.Name);
            ci.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
            Thread.CurrentThread.CurrentCulture = ci;
            InitializeComponent();
        }
        #endregion

        #region NavigationCheck
        private NavType NavigationCheck()
        {
            var url = new Uri(HtmlPage.Window.Eval("window.parent.location.href").ToString());
            var query = url.Query.ToLower();
            if (query.Length == 0)
            {
                
            }
            else
            {
                query = query.Remove(0, 1);
                string[] strings = query.Split('&');
                var parameters = strings.Select(s => s.Split('=')).ToDictionary(item => item[0], temp => temp[1]);
                string strNagivation = null;
                parameters.TryGetValue("navType".ToLower(), out strNagivation);
                QueryStringId = strNagivation;
                if (!string.IsNullOrEmpty(strNagivation))
                {
                    if (strNagivation.Equals("import", StringComparison.InvariantCultureIgnoreCase))
                    {                        
                        return NavType.Import;
                    }                   
                }
            }
            return NavType.NoDefined;
        }
        #endregion

        #region Application_Startup
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (e.InitParams.ContainsKey("CustomPageName"))
                CustomPageName = e.InitParams["CustomPageName"];

            if (e.InitParams.ContainsKey("CustomMainPageName"))
                CustomMainPageName = e.InitParams["CustomMainPageName"];

            if (e.InitParams.ContainsKey("LoginUserId"))
                LoginUserId = e.InitParams["LoginUserId"];

            if (e.InitParams.ContainsKey("UserGroupId"))
                UserGroupId = e.InitParams["UserGroupId"];

            if (e.InitParams.ContainsKey("UserName"))
                LoginUserName = e.InitParams["UserName"];

            if (e.InitParams.ContainsKey("Email"))
                LoginEmail = e.InitParams["Email"];

            if (e.InitParams.ContainsKey("Phone"))
                LoginPhone = e.InitParams["Phone"];

            if (e.InitParams.ContainsKey("PortalUrl"))
                PortalUrl = e.InitParams["PortalUrl"];

            if (e.InitParams.ContainsKey("HelpFilePath"))
                HelpFilePath = e.InitParams["HelpFilePath"];

            if (e.InitParams.ContainsKey("AoServicesUri"))
                AoServicesUri = e.InitParams["AoServicesUri"];
            else
            {
                string _serviceUri = String.Format("http://{0}/{1}", Application.Current.Host.Source.Host, "aoservices/"+FIFPConstants.RelationaDataUrl);
                Application.Current.Host.InitParams.Add(new KeyValuePair<string, string>("AoServicesUri", _serviceUri));
                AoServicesUri = _serviceUri;
            }
            //this.RootVisual = new MainDashBoard();

            NavType navType = NavigationCheck();
            
            if (navType == NavType.Import)
                this.RootVisual = new MainDashBoard();
            else
                this.RootVisual = new LandingPage();
        }
        #endregion

        #region Application_Exit
        private void Application_Exit(object sender, EventArgs e)
        {
        }
        #endregion
        
        #region Application_UnhandledException
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.


            //if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                //MessageBox.Show(e.ExceptionObject.Message);
                e.Handled = true;
                if (!_bMultiDBCallError)
                {
                    _bMultiDBCallError = true;
                    Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
                }
            }
        }
        #endregion

        #region ReportErrorToDOM
        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                //string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                //errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

               // System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
                System.Windows.Browser.HtmlPage.Window.Alert("throw new Error(\"Unhandled Error in Silverlight Application ");
            }
            catch (Exception ex)
            {
            }
        }
        #endregion

       
    }
}
